import java.math.BigInteger;

public class QueryStatistics {
	protected String sqlText;
	
	protected CommandType commandType;	
	protected long diskReads;		
	protected long bufferGets;		
	protected double elapsedTime;
	protected int executions;
	
	private void setCommandType(int commandType) {
		switch (commandType)
		{
		case 2:
			this.commandType = CommandType.INSERT;
			break;
		case 3:
			this.commandType = CommandType.SELECT;
			break;
		case 6:
			this.commandType = CommandType.UPDATE;
			break;
		case 7:
			this.commandType = CommandType.DELETE;
			break;
		case 189:
			this.commandType = CommandType.MERGE;
			break;
		default:
			this.commandType = CommandType.SELECT;
		}
	}
	
	QueryStatistics(String sqlText, long diskReads, long bufferGets, double elapsedTime, int commandType, int executions)
	{
		this.sqlText = sqlText;
		this.diskReads = diskReads;
		this.bufferGets = bufferGets;
		this.elapsedTime = elapsedTime;
		this.executions = executions;
		
		setCommandType(commandType);
	}
	
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((sqlText == null) ? 0 : sqlText.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		QueryStatistics other = (QueryStatistics) obj;
		if (sqlText == null) {
			if (other.sqlText != null)
				return false;
		} else if (sqlText.equals(other.sqlText))
			{
				/**
				 * Accumulate query statistics
				 */
				other.executions+=this.executions;
				other.bufferGets+=this.bufferGets;
				other.diskReads+=this.diskReads;
				other.elapsedTime+=this.elapsedTime;
				
			return true;
			}
		return false;
	}

	public String getSqlText() {
		return sqlText;
	}

	public CommandType getCommandType() {
		return commandType;
	}

	public long getDiskReads() {
		return diskReads;
	}

	public long getBufferGets() {
		return bufferGets;
	}

	public double getElapsedTime() {
		return elapsedTime;
	}

	public int getExecutions() {
		return executions;
	}
	
	public double getK()
	{
		StatisticsGenerator generator = new StatisticsGenerator();
		return generator.calculateRatio(this);
	}
}
